package com.RequestGongWuShu;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.yishun.springboot.pojo.UploadGWSAddTeam;
import com.yishun.springboot.dao.CWRServiceTest;
import com.yishun.springboot.pojo.GwsDictListJobName;
import com.yishun.springboot.pojo.GwsTeamType;

import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.junit.Test;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 实名制对接测试 注：方法上的注释打√的方法为对接测试环境测试数据已通过 √√的为对接测试环境正式数据已通过
 * 
 * @author YS
 * @date 2020/12/04 16:04
 */
@Slf4j
public class CWRService {

	private static final String URL = "http://szwb.sz.gov.cn:2018/";
	// 已修改为正确的
	private static String api_key = "25e73c16c13047dd828078aca3aa1523";
	private static String api_secret = "4577cfb17e014d0ba3ee940c54fcf87b";
	private static String client_serial = "25e73c16c13047dd828078aca3aa1523";
	private static String api_version = "1.0";

	private static String timestamp = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
	private static String Project_ID = "HG001267";// 工程编码

	private static String companyName = "一顺智能科技（广州）有限公司";// 供应商名称

	// 或许某些固定接口额外项
	private static String SUID = "914400001903237000";

	/**
	 * step1
	 * 
	 * step2实名制-获取工种 √
	 * 
	 * @throws NoSuchAlgorithmException
	 */
	public static List<GwsDictListJobName> getDictListJobName() throws NoSuchAlgorithmException {
		String url = "http://szwb.sz.gov.cn:2018/CWRService/DictListJobName";// 获取工种类型
		HashMap<String, Object> json = new HashMap<String, Object>();
		List<GwsDictListJobName> list = new ArrayList<GwsDictListJobName>();

		json.put("api_key", api_key);
		json.put("api_version", "1.0");
		json.put("client_serial", client_serial);
		json.put("timestamp", timestamp);
		json.put("body", "{}");
		String signature = getSignature(api_secret, (String) json.get("body"), (String) json.get("api_key"),
				(String) json.get("api_version"), (String) json.get("client_serial"), (String) json.get("timestamp"));
		json.put("signature", signature);
		log.info(JSONObject.toJSONString(json));
		String info = HttpUtil.post(url, json);
		log.info("info:" + info);
		JSONObject jsonObject = JSON.parseObject(info);
		String a = jsonObject.getString("result_data");
		JSONObject jsonObject2 = JSON.parseObject(a);
		String a2 = jsonObject2.getString("dict_list");
		JSONArray JsonArray = JSON.parseArray(a2);
		for (int i = 0; i < JsonArray.size(); i++) {
			String a3 = JsonArray.get(i).toString();
			GwsDictListJobName d = JSON.parseObject(a3, GwsDictListJobName.class);
			list.add(d);
		}
		return list;
		// 不用bean用什么获取result_data内容？
		// 工種類型：orders":"26","value":"电焊工","workerPostType":"COMMON","workerPostTypeName":"一般作业工种"},{"orders":"27","value":"爆破工",
		// 班組類型：[{"orders":"CONCRETE","value":"混凝土班","orderNum":0.0},{"orders":"waterproof","value":"防水班","orderNum":0.0,"typeAttribute":"00"}..]
	}

	/**
	 * 
	 * 
	 * step3 实名制-获取班组类型 √
	 * 
	 * @throws NoSuchAlgorithmException
	 */
	public static List<GwsTeamType> GetTeamType() throws NoSuchAlgorithmException {
		String url = "http://szwb.sz.gov.cn:2018/CWRService/GetTeamType";// 获取班组类型
		HashMap<String, Object> json = new HashMap<String, Object>();
		List<GwsTeamType> list = new ArrayList<GwsTeamType>();
		json.put("api_key", api_key);
		json.put("api_version", "1.0");
		json.put("client_serial", client_serial);
		json.put("timestamp", timestamp);
		json.put("body", "{}");
		String signature = getSignature(api_secret, (String) json.get("body"), (String) json.get("api_key"),
				(String) json.get("api_version"), (String) json.get("client_serial"), (String) json.get("timestamp"));
		json.put("signature", signature);
		log.info(json.toString());
		String info = HttpUtil.post(url, json);
		log.info("info:" + info);
		JSONObject jsonObject = JSON.parseObject(info);
		String a = jsonObject.getString("result_data");
		JSONObject jsonObject2 = JSON.parseObject(a);
		String a2 = jsonObject2.getString("dict_list");
		JSONArray JsonArray = JSON.parseArray(a2);
		for (int i = 0; i < JsonArray.size(); i++) {
			String a3 = JsonArray.get(i).toString();
			GwsTeamType t = JSON.parseObject(a3, GwsTeamType.class);
			list.add(t);
			log.info("bean:" + t.toString());
		}
		return list;

		// 不用bean用什么获取result_data内容？
		// 工種類型：orders":"26","value":"电焊工","workerPostType":"COMMON","workerPostTypeName":"一般作业工种"},{"orders":"27","value":"爆破工",
		// 班組類型：[{"orders":"CONCRETE","value":"混凝土班","orderNum":0.0},{"orders":"waterproof","value":"防水班","orderNum":0.0,"typeAttribute":"00"}..]
	}

	/**
	 * step4 实名制-新增班组√ AddTeam接口
	 */
	public static String addTeam(UploadGWSAddTeam d) {
		String url = "http://szwb.sz.gov.cn:2018/CWRService/AddTeam";
		JSONObject json = new JSONObject(true); // JSONObject数据排序（顺序）问题 加个true意思是按put的顺序排序
		json.put("Project_ID", "HG001267");
		json.put("team_name", "泥工班组");
		json.put("team_type_order", "CONCRETE");// 3.1.4接口
		json.put("team_type_name", "混凝土班");// 3.1.4接口
		json.put("emp_company", "中建三局集团有限公司");
		json.put("SUID", "91420000757013137P");

		JSONObject jsonObj = new JSONObject(new LinkedHashMap());

		String j2r = JSONObject.toJSONString(d, SerializerFeature.QuoteFieldNames,
				SerializerFeature.WriteNullStringAsEmpty);
//		String j2r = JSON.toJSONString(d,SerializerFeature.QuoteFieldNames,SerializerFeature.WriteNullStringAsEmpty);

		JSONObject json2 = JSONObject.parseObject(j2r);
		String body2 = JSON.toJSONString(json2);
		String info = "";

		String body = json.toString();
		log.info("sha:" + body);
		log.info("xia:" + body2);

		try {
			String signature = getSignature(api_secret, body, api_key, api_version, client_serial, timestamp);
			String signature2 = getSignature(api_secret, body2, api_key, api_version, client_serial, timestamp);
			log.info("sha:" + signature);
			log.info("xia:" + signature2);
			log.info("duibi-----");
			log.info("b1:" + body);
			log.info("b2:" + body2);

			Map<String, Object> param = new HashMap<>();
			param.put("api_version", api_version);
			param.put("client_serial", client_serial);
			param.put("api_key", api_key);
			param.put("timestamp", timestamp);
			param.put("signature", signature);
			param.put("body", body);
			info = HttpUtil.post(url, param);
			log.info(info);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return info;
		// {"team_id":"6014985e9877f6dfc0633b0601ce2612","team_name":"渣渣輝"}}
	}

	public static void main(String[] args) {

		try {
			log.info(GetTeamType().toString());
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * step5 实名制-上传图片√√ 这个不用大改，所以直接打了第二个√，该是什么样就什么样
	 */
	public String UploadImage(String filePath) {

//		File file = new File("C:\\Users\\Administrator\\Desktop\\3.JPG");
		File file = new File(filePath);
		String url = "http://szwb.sz.gov.cn:2018/CWRService/UploadImage";
		Map<String, Object> param = new HashMap<>();
		param.put("api_key", api_key);
		param.put("file", file);
		String info = HttpUtil.post(url, param);
		log.info(info); // 每次上傳如果相同的照片，返回的image_id也不同

		JSONObject jsonObject = JSON.parseObject(info);
		String a = jsonObject.getString("result_data");
		log.info("a:" + a);

		return "";

		// {"result":"true","code":"00","status":"200","message":"成功","result_data":{"image_id":"8fc3c24d06b59e19fc211c3b5bf1113c"}}
	}

	// 获取文件，因为web需要而不是路径
	public String UploadImage(MultipartFile multipartFile) {

		String fileName = multipartFile.getOriginalFilename();
		File file = new File(fileName);
		log.info("files:" + file.getPath());
		OutputStream out = null;
		try {
			// 获取文件流，以文件流的方式输出到新文件
//		    InputStream in = multipartFile.getInputStream();
			out = new FileOutputStream(file);
			byte[] ss = multipartFile.getBytes();
			for (int i = 0; i < ss.length; i++) {
				out.write(ss[i]);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

//		File file = new File("C:\\Users\\Administrator\\Desktop\\3.JPG");
		String url = "http://szwb.sz.gov.cn:2018/CWRService/UploadImage";
		Map<String, Object> param = new HashMap<>();
		param.put("api_key", api_key);
		param.put("file", file);
		String info = HttpUtil.post(url, param);
		log.info(info); // 每次上傳如果相同的照片，返回的image_id也不同

		JSONObject jsonObject = JSON.parseObject(info);
		String results = jsonObject.getString("result_data");

		return results;

		// {"result":"true","code":"00","status":"200","message":"成功","result_data":{"image_id":"8fc3c24d06b59e19fc211c3b5bf1113c"}}
	}

	/**
	 * step6 实名制-上报人员实名制信息
	 */
	public void RegisterEmployee() {
		String url = "http://szwb.sz.gov.cn:2018/CWRService/RegisterEmployee";
		JSONObject json = new JSONObject();
		json.put("Project_ID", Project_ID);
		json.put("id_code", "110101198001010053");
		json.put("id_photo", "8fc3c24d06b59e19fc211c3b5bf1113c");// 图片接口获取，上传图片返回的id
		json.put("emp_name", "一顺小瓜");
		json.put("emp_phone", "15006017815");
		json.put("emp_nativeplace", "广州身份证地址");
		json.put("emp_nation", "壮族");
		json.put("match_flag", "Y");
		json.put("facephoto", "0157de08946b420397fc78272676d6d3");
		json.put("emp_company", companyName);
		json.put("SUID", SUID);
		json.put("team_id", "a881e98c4a4ff3168800a62c18329931");// team_id 来自 ADDTEAM接口的返回值
		json.put("team_name", "焊工班008");
		json.put("emp_category", "00");
		json.put("job_order", "27");
		json.put("job_name", "爆破工");
		json.put("contract_status", "1");
		String body = json.toString();
		try {
			String signature = getSignature(api_secret, body, api_key, api_version, client_serial, timestamp);
			Map<String, Object> param = new HashMap<>();
			param.put("api_version", api_version);
			param.put("client_serial", client_serial);
			param.put("api_key", api_key);
			param.put("timestamp", timestamp);
			param.put("signature", signature);
			param.put("body", body);
			String info = HttpUtil.post(url, param);
			log.info(info);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * step7 实名制-上传考勤信息
	 */
	public void UploadPassedLog() {
		String url = "http://szwb.sz.gov.cn:2018/CWRService/UploadPassedLog";// 不知道什么呢
		JSONObject json = new JSONObject();
		json.put("Project_ID", Project_ID);
		json.put("Device_ID", "0001");

		List<JSONObject> passedlog_list = new ArrayList<>();
		JSONObject passedlog = new JSONObject();
		passedlog.put("data_id", api_key + UUID.randomUUID().toString().replace("-", ""));// 数据的唯一id
		passedlog.put("person_type", "1");
		passedlog.put("person_id", "110101198001010053");
		passedlog.put("person_name", "一顺小瓜");
		passedlog.put("passed_time", timestamp);
		passedlog.put("direction", "in");
		passedlog.put("way", "1");
		passedlog.put("site_photo", "8fc3c24d06b59e19fc211c3b5bf1113c");
		passedlog.put("address", "北京天安门南路西北路口东大道");
		passedlog_list.add(passedlog);

		json.put("passedlog_list", passedlog_list);
		String body = json.toString();
		try {
			String signature = getSignature(api_secret, body, api_key, api_version, client_serial, timestamp);
			Map<String, Object> param = new HashMap<>();
			param.put("api_version", api_version);
			param.put("client_serial", client_serial);
			param.put("api_key", api_key);
			param.put("timestamp", timestamp);
			param.put("signature", signature);
			param.put("body", body);
			String info = HttpUtil.post(url, param);
			log.info(info);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * step7 实名制-人员离场√
	 */
	public void userLeaveProject() {
		String url = "http://szwb.sz.gov.cn:2018/CWRService/userLeaveProject";// 不知道什么呢
		JSONObject json = new JSONObject();
		json.put("Project_ID", Project_ID);

		List<JSONObject> userLeaveProject_list = new ArrayList<>();
		JSONObject passedlog = new JSONObject();
		passedlog.put("id_code", "110101198001010053");
		passedlog.put("exit_time", timestamp);
		userLeaveProject_list.add(passedlog);

		json.put("userLeaveProject_list", userLeaveProject_list);
		String body = json.toString();
		try {
			String signature = getSignature(api_secret, body, api_key, api_version, client_serial, timestamp);
			Map<String, Object> param = new HashMap<>();
			param.put("api_version", api_version);
			param.put("client_serial", client_serial);
			param.put("api_key", api_key);
			param.put("timestamp", timestamp);
			param.put("signature", signature);
			param.put("body", body);
			String info = HttpUtil.post(url, param);
			log.info(info);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * step7 实名制-人员离场√ 可多人离场√
	 */
	public static JSONObject userLeaveProject(JSONObject paramJson) {
		String url = URL + "CWRService/userLeaveProject";

		LocalDateTime date = LocalDateTime.now();
		DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		String timestamp = dateFormatter.format(date);

		String body = paramJson.toString();

		try {
			String signature = getSignature(api_secret, body, api_key, api_version, client_serial, timestamp);
			Map<String, Object> param = new HashMap<>();
			param.put("api_version", api_version);
			param.put("client_serial", client_serial);
			param.put("api_key", api_key);
			param.put("timestamp", timestamp);
			param.put("signature", signature);
			param.put("body", body);
			String info = HttpUtil.post(url, param);

			return JSONObject.parseObject(info);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * @param api_secret    授权秘钥
	 * @param body          请求体
	 * @param api_Key       授权帐号
	 * @param api_Version   API协议版本
	 * @param client_Serial 第三方系统编号 可以取值
	 * @param timeStamp     时间戳，格式为yyyy-MM-dd hh:mm:ss
	 * @return boolean
	 * @Description:拼接加密参数
	 * @author fanghe 2017年3月25日 上午11:44:50
	 */
	private static String getSignature(String api_secret, String body, String api_Key, String api_Version,
			String client_Serial, String timeStamp) throws NoSuchAlgorithmException {
		StringBuilder str4MD5 = new StringBuilder();
		str4MD5.append(api_secret).append("api_key").append(api_Key).append("api_version").append(api_Version)
				.append("body").append(StrUtil.isEmpty(body) ? "{}" : body).append("client_serial")
				.append(client_Serial).append("timestamp").append(timeStamp).append(api_secret);
//		log.info(str4MD5.toString());
		String str = GetMD5Code(str4MD5.toString());
		return str;
	}

	/**
	 * Description: 获取32位大写MD5加密
	 *
	 * @param strObj 原文
	 * @return 32位大写MD5加密
	 * @see
	 */
	public static String GetMD5Code(String strObj) throws NoSuchAlgorithmException {
		String resultString = null;
		resultString = new String(strObj);
		MessageDigest md = MessageDigest.getInstance("MD5");
		Charset charset = Charset.forName("UTF-8");
		// md.digest() 该函数返回值为存放哈希值结果的byte数组
		resultString = byteToString(md.digest(strObj.getBytes(charset)));
		return resultString;
	}

	/**
	 * Description: 转换字节数组为16进制字串
	 *
	 * @param bytes 字节数组
	 * @return 16进制字串
	 * @see
	 */
	private static String byteToString(byte[] bytes) {
		StringBuffer sBuffer = new StringBuffer();
		for (int i = 0; i < bytes.length; i++) {
			sBuffer.append(byteToArrayString(bytes[i]));
		}
		return sBuffer.toString();
	}

	/**
	 * Description: 返回形式为数字跟字符串(大写)
	 *
	 * @param bByte 字节
	 * @return 返回形式为数字跟字符串(大写)
	 * @see
	 */
	private static String byteToArrayString(byte bByte) {
		int iRet = bByte;
		if (iRet < 0) {
			iRet += 256;
		}
		int iD1 = iRet / 16;
		int iD2 = iRet % 16;
		return strDigits[iD1] + strDigits[iD2];
	}

	/**
	 * 全局数组
	 */
	private final static String[] strDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D",
			"E", "F" };

	/**
	 * 签名的生成 签名测试
	 *
	 * @throws NoSuchAlgorithmException
	 */
	public void createSignature() throws NoSuchAlgorithmException {
		String signature = getSignature(api_secret,
				"{\"entry_time\":\"2019-07-01 02:56:05\",\"Legal_Person\":\"罗世威\",\"Type\":\"009\",\"Project_ID\":\"XM2013031101\",\"Company_Name\":\"中国建筑一局(集团)有限公司\"}",
				api_key, api_version, client_serial, timestamp);
		log.info(signature);
		// 如果body为空
		String signature2 = getSignature(api_secret, null, api_key, api_version, client_serial, timestamp);
		log.info(signature2);
	}

	public static void setApi_key(String api_key) {
		CWRService.api_key = api_key;
	}

	public static void setApi_secret(String api_secret) {
		CWRService.api_secret = api_secret;
	}

	public static void setClient_serial(String client_serial) {
		CWRService.client_serial = client_serial;
	}

	public static void setApi_version(String api_version) {
		CWRService.api_version = api_version;
	}

}
